package com.woniu.dao.impl;

import com.woniu.entity.Student;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.Scanner;

public class JdbcUnit {
    static Connection connection() throws Exception{
        String ClassName = "com.mysql.cj.jdbc.Driver";
        Class.forName(ClassName);
        String url = "jdbc:mysql:///db1";
        String user="root";
        String password="123";
        Connection connection = DriverManager.getConnection(url, user, password);
        return connection;
    }
    static void close(PreparedStatement preparedStatement, Connection connection, ResultSet resultSet) throws SQLException {
        if(preparedStatement != null) {
            preparedStatement.close();
        }
        if(connection != null) {
            connection.close();
        }
        if(resultSet != null) {
            resultSet.close();
        }
    }

    static void xxx( Connection connection,String sql,Object... objects) throws Exception {
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        Scanner sc = new Scanner(System.in);
        if(objects != null) {
            for(int i = 0;i < objects.length;i++) {
                preparedStatement.setObject(i+1,objects[i]);
            }
        }
        int count = preparedStatement.executeUpdate();
        close(preparedStatement,connection,null);
    }

    static <T> void ttt(Connection connection,String sql,Class<T> clazz,Object... objects) throws Exception {
        T student = (T) clazz.newInstance();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        if(objects != null) {
            for(int i = 0;i < objects.length;i++) {
                preparedStatement.setObject(i+1,objects[i]);
            }
        }
        ResultSet resultSet = preparedStatement.executeQuery();
        if(resultSet.next()){
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object columnValue = resultSet.getObject(columnName);
                try {
                    Field declaredField = clazz.getDeclaredField(columnName);
                    declaredField.setAccessible(true);
                    declaredField.set(student,columnValue);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        System.out.println(student);
        close(preparedStatement,connection,resultSet);
    }

}
